<?php
namespace Swork\Pool\Amqp;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use Swork\Exception\AmqpException;
use Swork\Pool\AbstractConnection;
use Swork\Service;

/**
 * Interface ConnectInterface
 * @package Swoft\Pool
 */
class AmqpConnection extends AbstractConnection
{
    /**
     * 当前连接对象
     * @var AMQPStreamConnection
     */
    private $connection;

    /**
     * @return AMQPStreamConnection|false
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * Create connectioin
     * @return void
     * @throws
     */
    public function create()
    {
        //获取参数
        $opts = $this->config->getUri();

        //合并参数
        $opts = array_merge([
            'host' => '127.0.0.1',
            'port' => 5672,
            'user' => 'guest',
            'password' => 'guest',
        ], $opts);

        //创建连接
        try
        {
            $this->connection = new AMQPStreamConnection($opts['host'], $opts['port'], $opts['user'], $opts['password']);
            if ($this->connection == false)
            {
                throw new AmqpException('Amqp connect failed');
            }
        }
        catch (\Throwable $throwable)
        {
            Service::$logger->error('AMQP: ' . $throwable->getMessage());
        }
    }

    /**
     * 重新连接
     * @throws
     */
    public function reconnect()
    {
        $this->create();
    }

    /**
     * 检查是否连接中
     * @return bool
     */
    public function check(): bool
    {
        return $this->connection->isConnected();
    }
}
